class Solution {
    /*
        大佬优雅的代码
    */
    public static String reverseWords(String s) {
        StringBuilder ans = new StringBuilder();
        int i = s.length()-1;
        while(i>=0){
            int count = 0;
            while(i>=0 && s.charAt(i)==' ')
                i--;
            while( i>=0 && s.charAt(i)!=' ' ){
                i--;
                count++;
            }
            if(count>0) // " a"的这种情况
                ans.append(s.substring(i+1,i+count+1)+" ");
        }
        return ans.substring(0,ans.length()-1);
    }
}
/*
        自己写的不够优雅的代码
*/
class Solution {
    boolean flag = true;
    StringBuilder ans = new StringBuilder();
    public String reverseWords(String s) {
        s = " "+s+" ";
        int last = s.length()-2;
        while (true){
            int[] res = find(s, last);
            last = res[0]-2;
            if(res[0]==-1)
                break;
        }

        return ans.toString();
    }
    public int[] find(String s,int index){
        int res1 = -1,res2 = -1;
        for(int i=index; i>=0; i--){
            if(s.charAt(i)!=' ' && s.charAt(i+1)==' '){
                res2 = i;
            }
            if(s.charAt(i)!=' ' && s.charAt(i-1)==' '){
                res1 = i;
                if(!flag) ans.append(" ");
                if(flag) flag = false;
                ans.append(s.substring(res1,res2+1));
                // System.out.print(s.substring(res1,res2+1));
                
                return new int[]{res1,res2};
            }
        }
        return new int[]{-1,-1};
    }
}